package user_api

import (
	"blogx_server/common/res"
	"blogx_server/global"
	"blogx_server/models"
	"blogx_server/models/enum"
	"blogx_server/service/log_service"
	"blogx_server/service/user_service"
	"blogx_server/utils/jwts"
	"blogx_server/utils/pwd"
	"github.com/gin-gonic/gin"
)

type PwdLoginRequest struct {
	Val      string `json:"val"` //可能是用户名 可能是邮箱
	Password string `json:"password"`
}

func BingJson[T any](c *gin.Context) (cr T) {
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(err, c)
		return
	}
	return
}

func (UserApi) PwdLoginApi(c *gin.Context) {
	var cr PwdLoginRequest
	err := c.ShouldBind(&cr)
	if err != nil {
		res.FailWithError(err, c)
		return
	}

	if !global.Config.Site.Login.UsernamePwdLogin {
		res.FailWithMsg("站点未启用密码登录", c)
		return
	}

	var user models.UserModel

	err = global.DB.Debug().Take(&user, "(username = ? or email = ?) and password <> ''	",
		cr.Val, cr.Val).Error

	if err != nil {
		log_service.NewLoginFail(c, enum.UserPwdLoginType, "用户名密码错误", user.Username)
		res.FailWithMsg("用户名密码错误", c)
		return
	}

	if !pwd.CompareHashAndPassword(user.Password, cr.Password) {
		log_service.NewLoginFail(c, enum.UserPwdLoginType, "用户名密码错误", user.Username)
		res.FailWithMsg("用户名密码错误", c)
		return
	}

	//颁发token
	token, _ := jwts.GetToken(jwts.Claims{
		UserID:   user.ID,
		Username: user.Username,
		Role:     user.Role,
	})

	log_service.NewLoginSuccess(c, enum.UserPwdLoginType)
	user_service.NewUserService(user).UserLogin(c)
	res.OkWithData(token, c)
}
